import axios from 'axios'

import qs from './qs.js'

export default (Vue) => {
  axios.interceptors.request.use(config=>{
    let url = config.url
    if(config.method === "get" && config.params){
      url += "?"
      let keys = Object.keys(config.params)
      url += keys.map(key=>{
        return `${key}=${encodeURIComponent(config.params[key])}`
      }).join("&")
      config.params = {}
    }
    config.url = url
    return config
  })
  
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

  Vue.prototype.$axios = axios
  Vue.prototype.$qs = qs
  //便捷处理提示的参数
  const ajaxTip = function (cfg, message) {
    if (cfg.tip != false) {
      Vue.prototype.$message.error(message)
    }
  }
  //便捷处理提示的拒绝的情况,fail回调会覆盖默认的错误处理，failure为后续错误处理
  const ajaxFail = function (cfg, defaultfail, ...failparams) {

    if (cfg.fail) {
      cfg.fail(...failparams)
    } else if (defaultfail) {
      defaultfail()
    }
    if (cfg.failure) cfg.failure(...failparams)
    if (cfg.complete) cfg.complete()
  }
  Vue.prototype.$ajax = function (cfg) {

    if (cfg.method) {

    } else {
      cfg.method = 'post'
    }
    if (cfg.type == 'json') {
      cfg.headers = Object.assign({}, cfg.headers, { 'content-type': 'application/json' })
    }

    var tmpIndex = cfg.url.indexOf('?')
    var targetUrl = cfg.url

    if (tmpIndex !== -1) {
      targetUrl = cfg.url.substring(0, tmpIndex)
      var appendParams = cfg.url.substring(tmpIndex + 1)
      if (appendParams !== '') {
        var tmpStrings = appendParams.split('&')
        if (tmpStrings.length > 0) {
          if (!cfg.data) {
            cfg.data = {}
          }
          for (var i = 0, len = tmpStrings.length; i < len; i++) {
            var tmpsValues = tmpStrings[i].split('=')

            if (tmpsValues.length > 1) {
              cfg.data[tmpsValues[0] + ''] = tmpsValues[1]
            }
          }
        }
      }
      cfg.url = targetUrl
    }
    if (cfg.data instanceof Array) {

    } else if (Vue.prototype.$ex_ajax_extra_data) {
      cfg.data = Object.assign({}, cfg.data, Vue.prototype.$ex_ajax_extra_data)
    }
    if (Vue.prototype.$ex_ajax_extra_header) {
      cfg.headers = Object.assign({}, cfg.headers, Vue.prototype.$ex_ajax_extra_header)
    }
    if (cfg.method == 'get') {
      cfg.params = cfg.data
    }
    let postData
    if (cfg.type && cfg.type === 'json') {
      postData = JSON.stringify(cfg.data)
    } else {
      postData = this.$qs.stringify(cfg.data)
    }


    cfg.data = postData


    let loading = null
    if (cfg.loading) {
      let _loadObj = {
        lock: true,
        text: '加载中',
      }
      if (cfg.loading instanceof String) {
        _loadObj.text = cfg.loading
      } else if (cfg.loading instanceof Object) {
        Object.assign(_loadObj, cfg.loading)
      }
      loading = this.$loading(_loadObj);
    }

    axios(cfg)
      .then((response) => {
        if (loading) loading.close();
        if (cfg.callback) {
          cfg.callback(response)
          return
        }

        if (response.status !== 200) {
          return ajaxFail(cfg, () => ajaxTip(cfg, '服务器异常：' + response.message), response.data, response.config)
        }

        var responseData = response.data

        if (!responseData) return ajaxFail(cfg, () => ajaxTip(cfg, '服务器没有返回数据'), response.data, response.config)


        if (responseData.code === 0 || (cfg.isSuccess && cfg.isSuccess(responseData))) {
          if (cfg.success) cfg.success(responseData, response.config)
        } else {

          return ajaxFail(cfg, () => {
            switch (responseData.code) {
              default: {
                if (responseData.message && responseData.message.indexOf('Data too long for column') !== -1) {
                  ajaxTip(cfg, '数据字段超长')
                } else {
                  ajaxTip(cfg, responseData.message || "服务异常")
                }
                break
              }
              case 401: {
                if (Vue.prototype.$ex_default_login_url) {
                  window.location.href = Vue.prototype.$ex_default_login_url
                } else {
                  window.location.href = '/login.htm'
                }
                break
              }
              case 403: {
                ajaxTip(cfg, '权限异常:' + responseData.message)
                break
              }
              case 500: {
                ajaxTip(cfg, responseData.message)
                break
              }
            }
          }, response.data, response.config)
        }

        if (cfg.afterAjax) {
          cfg.afterAjax(responseData, response.config.scope)
        }
        if (cfg.complete) {
          cfg.complete()
        }
      })
      .catch((error) => {
        console.error(error)
        if (loading) loading.close();

        ajaxFail(cfg, () => ajaxTip(cfg, '异常：' + error))

      })
  }
}
